function results = am_moran(results)
% PURPOSE: compute moran scatterplot figure
% returns an n x 3 matrix of colors that can be used to label the map polygons
% and a handle to the legend figure

cmap = results.cmap;
nbc = results.nbc;
vindex = results.vindex;
vflag = results.vflag;

cvariable = results.cvariable; 
WX = results.WX(:,vindex);
obs_selected = results.obs_selected;
nobs = length(obs_selected);
if vflag == 1
vname = results.vnames(vindex,:);
elseif vflag == 0
vname = results.vnames(vindex+1,:);
end;

Q0 = results.Q0;
Q1 = results.Q1;
Q2 = results.Q2;
Q3 = results.Q3;
Q4 = results.Q4;


if (results.moran_fig == 0)
	if results.legendmenu == 0
	moran_fig = figure('Position',[results.width+60 100 400 400], ... % [left bottom width height]
                      'NumberTitle','off', ...
                      'Name','Moran Scatterplot', ...
                      'MenuBar','none');
	elseif results.legendmenu == 1
	moran_fig = figure('Position',[results.width+60 100 400 400], ... % [left bottom width height]
                      'NumberTitle','off', ...
                      'Name','Moran Scatterplot');
	end;
results.moran_fig = moran_fig;
else
figure(results.moran_fig);
end;

hc = colormap(cmap);
% hc is always 64 by 3 matrix
incr = floor(64/nbc);
cindex = 1:incr:64;
cindex = cindex(1:nbc);
hcolor = hc(cindex,:);

map_colors = ones(nobs,3);
for i=1:3;
map_colors(Q0,i) = 1;
map_colors(Q1,i) = hcolor(1,i);
map_colors(Q2,i) = hcolor(2,i);
map_colors(Q3,i) = hcolor(3,i);
map_colors(Q4,i) = hcolor(4,i);
end;
results.map_colors = map_colors;

if nobs > 1000
msize = 4;
elseif nobs > 100
msize = 8;
elseif nobs > 50
msize = 16;
else
msize = 32;
end;

good = find(results.cmissing == 1);

m_fig = scatter('v6',cvariable,WX,msize,hcolor(1,:));
set(m_fig,'Visible','off');
set(m_fig(Q0),'MarkerEdgeColor',[1 1 1]);
set(m_fig(Q1),'MarkerEdgeColor',hcolor(1,:));
set(m_fig(Q2),'MarkerEdgeColor',hcolor(2,:));
set(m_fig(Q3),'MarkerEdgeColor',hcolor(3,:));
set(m_fig(Q4),'MarkerEdgeColor',hcolor(4,:));
axis normal;
set(m_fig(obs_selected),'Visible','on');

% try keying this only on selected observations
% for the case of a zoom
tmpvariable = cvariable(results.obs_selected,1);
tmpWX = WX(results.obs_selected,1);

xbuffer = 0.5*abs(0.1*min(tmpvariable));
ybuffer = 0.1*min(tmpWX);

maxx = max(tmpvariable);
minx = min(tmpvariable);
maxy = max(tmpWX);
miny = min(tmpWX);

axis([1.1* minx 1.1*maxx 1.1*miny 1.1*maxy]);

line([1.1*minx 1.1*maxx],[0 0],'Color','black');
line([0 0],[1.1*miny 1.1*maxy],'Color','black');
axis manual;

  if results.labels == 1
	for i=1:length(obs_selected);
    j = obs_selected(i,1);
	hi = text(cvariable(j)+xbuffer,WX(j),num2str(j));
	set(hi,'fontsize',6);
	end;
  end;

set(results.moran_fig,'Visible','on');
xlabel(vname);
mname = ['W*',vname];
ylabel(mname);


